public class IsBalanced {//leecode 110

    public boolean isBalanced(TreeNode root) {
        int x=func(root);
        if(x<0){
            return false;
        }else{
            return true;
        }

    }

    public int func(TreeNode root){//求深度的同时判断左右子树是否平衡，即左右子树高度差小于2
        if(root==null) return 0;
        int left=func(root.left);
        if(left<0) return -1;
        int right=func(root.right);
        if(right<0) return -1;
        if(Math.abs(right-left)>=2){
            return -1;
        }
        return 1+Math.max(right,left);
    }
}
